package com.hbnu.mysql.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*
 * @author zouting
 * @Date 2025-11-05-10:26
 *
 */public class RegisterService extends LRService {
    /**
     * 初始化注册界面，获取用户注册信息
     *
     * @return 包含用户名和密码的Map集合
     */
    @Override
    public Map<String, String> initRegisterUI(Scanner scanner) {

        Map<String, String> userInfo = new HashMap<>();
        //注册的流程
        System.out.print("请输入要注册的用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        System.out.print("请输入地址: ");
        String address = scanner.nextLine();
        System.out.print("请输入手机号: ");
        String phone = scanner.nextLine();


        userInfo.put("username", username);
        userInfo.put("password", password);
        userInfo.put("address", address);
        userInfo.put("phone", phone);

        return userInfo;
    }

    /**
     * 注册新用户
     *
     * @param userInfo 包含用户名和密码的Map集合
     * @return 注册成功返回true，否则返回false
     */
    @Override
    public boolean registerUser(Map<String, String> userInfo) {
        String username = userInfo.get("username");
        String password = userInfo.get("password");
        String address = userInfo.get("address");
        String phone = userInfo.get("phone");


        // 判断用户名是否已存在
        if (isUsernameExists(username)) {
            System.out.println("用户名已存在，请选择其他用户名");
            return false;
        }

        String sql = "INSERT INTO tb_user (username,password,address,phone,role) VALUES (?,?,?,?,?)";

        try (Connection connection = LRService.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            preparedStatement.setString(3, address);
            preparedStatement.setString(4, phone);
            preparedStatement.setString(5, "0");//设置用户角色为普通用户


            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0; // 插入成功返回true
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
 }
